package com.umakr.ax.app.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.umakr.ax.common.mapper.MsgMapper;
import com.umakr.ax.common.mapper.RadioStationMapper;
import com.umakr.ax.common.model.Msg;
import com.umakr.ax.common.model.RadioStation;
import com.umakr.ax.common.model.RadioStationFollower;
import com.umakr.ax.common.service.*;
import com.umakr.ax.common.util.AliyunPushUtil;
import com.umakr.ax.common.vo.MsgSeekHelpInfoVO;
import com.umakr.ax.core.base.BaseService;
import com.umakr.ax.utils.AudioUtil;
import com.umakr.ax.utils.FormatPhotoUrlUtil;
import com.umakr.ax.utils.WebUtil;
import com.umakr.ax.wechat.util.SpeedStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author tangtengfei
 */
@Service
public class MsgWebService  extends BaseService<MsgMapper, Msg> {

    @Autowired
    MsgService msgService;
    @Autowired
    SeekHelpInfoService seekHelpInfoService;
    @Autowired
    RadioStationFollowerService radioStationFollowerService;
    @Autowired
    UserScoreService userScoreService;
    @Autowired
    RadioStationMapper radioStationMapper;
    @Autowired
    RadioStationService radioStationService;

    @Autowired
    Environment env;

    public boolean save(Msg msg) {
        return msgService.insert(msg);
    }

    public boolean saveFromWechat(String msgAttachmentAddr, String msgTxtContent, Date msgTime, Integer msgContentType, Integer radioLen, String positionCoor, String positionName, Long rsId, Long userId, Map<String, String> wechatIdData, Map<String, String> wechatMsgData, Map<String, String> wechatUserData) {
        //0互动
        Integer msgType = 0;
        //0 用户->电台
        Integer msgDirect = 0;
        //0待审
        Integer status = 0;
        //0微信
        Integer messageFrom = 0;
        return msgService.insertForWechat(msgAttachmentAddr, msgTxtContent, msgTime, msgContentType, radioLen, positionCoor, positionName, rsId, userId,
                SpeedStorage.gson.toJson(wechatIdData), SpeedStorage.gson.toJson(wechatMsgData), SpeedStorage.gson.toJson(wechatUserData),
                msgType, msgDirect, status, messageFrom);
    }

    public Page<MsgSeekHelpInfoVO> listMsg(Long rsId, Integer status, Date latestTime) {
        String aliUrl = env.getProperty("oss.img.path");
        String localUrl = env.getProperty("native.resource.path");
        String defaultAvatar = env.getProperty("user.default.avatar");

        Page<MsgSeekHelpInfoVO> page = baseMapper.listMsg(rsId,status,latestTime);
        for (MsgSeekHelpInfoVO msgSeekHelpInfoVO : page.getRecords()){

            if(msgSeekHelpInfoVO.getMsgDirect() == 2){
                msgSeekHelpInfoVO.setNickname(msgSeekHelpInfoVO.getRsName());
                msgSeekHelpInfoVO.setHeadimgurl(aliUrl+msgSeekHelpInfoVO.getRsLogo());
            }else{
                if(msgSeekHelpInfoVO.getUserId() == -1){
                    if(msgSeekHelpInfoVO.getWechatUserData() != ""){
                        JSONObject json = JSONObject.parseObject(msgSeekHelpInfoVO.getWechatUserData());
                        msgSeekHelpInfoVO.setHeadimgurl(json.get("headimgurl") == null ?  aliUrl+defaultAvatar :  json.getString("headimgurl"));
                        msgSeekHelpInfoVO.setNickname(json.get("nickname") == null ? "" :  json.getString("nickname"));
                    }
                }else if(msgSeekHelpInfoVO.getUserId() == -2){
                    msgSeekHelpInfoVO.setHeadimgurl( aliUrl+defaultAvatar);
                    msgSeekHelpInfoVO.setNickname("webApp用户");
                }else {
                    msgSeekHelpInfoVO.setHeadimgurl(FormatPhotoUrlUtil.formatString(aliUrl,msgSeekHelpInfoVO.getHeadimgurl()));
                }

            }


            //设置历史消息路径:只要是互动的语音消息都是本地的
            if(msgSeekHelpInfoVO.getMsgAttachmentAddr() == null){
                msgSeekHelpInfoVO.setMsgAttachmentAddr("");
            }else {
                if(msgSeekHelpInfoVO.getMsgContentType() == 1 || msgSeekHelpInfoVO.getMsgContentType() ==2){
                    if(msgSeekHelpInfoVO.getMsgType() == 0 && msgSeekHelpInfoVO.getMsgContentType() == 1){
                        msgSeekHelpInfoVO.setMsgAttachmentAddr(localUrl+msgSeekHelpInfoVO.getMsgAttachmentAddr());
                    }else {
                        msgSeekHelpInfoVO.setMsgAttachmentAddr(aliUrl+msgSeekHelpInfoVO.getMsgAttachmentAddr());
                    }
                }
            }
            //设置图片路径
            msgSeekHelpInfoVO.setPhotoInfo(FormatPhotoUrlUtil.formatStringArray(aliUrl,msgSeekHelpInfoVO.getPhotoInfo()));
            //设置求助语音消息路径
            if(msgSeekHelpInfoVO.getSeekVoice() == null || "".equals(msgSeekHelpInfoVO.getSeekVoice().replace(" ",""))){
                msgSeekHelpInfoVO.setSeekVoice("");
            }else {
                msgSeekHelpInfoVO.setSeekVoice(aliUrl+msgSeekHelpInfoVO.getSeekVoice());
            }
        }
        WebUtil.addParamToPage(page,"latestTime",latestTime);
        return page;
    }
    public Object listMoreMsg(Long rsId, Integer status, Date latestTime) {
        String aliUrl = env.getProperty("oss.img.path");
        String localUrl = env.getProperty("native.resource.path");
        String defaultAvatar = env.getProperty("user.default.avatar");
        int errorCode = 1 ;
        String msg = "获取成功";
        List<MsgSeekHelpInfoVO> list = baseMapper.listMoreMsg(rsId,status,latestTime);
        for (MsgSeekHelpInfoVO msgSeekHelpInfoVO : list){

            if(msgSeekHelpInfoVO.getMsgDirect() == 2){
                msgSeekHelpInfoVO.setNickname(msgSeekHelpInfoVO.getRsName());
                msgSeekHelpInfoVO.setHeadimgurl(aliUrl+msgSeekHelpInfoVO.getRsLogo());
            }else{
                if(msgSeekHelpInfoVO.getUserId() == -1){
                    if(msgSeekHelpInfoVO.getWechatUserData() != "" && msgSeekHelpInfoVO.getWechatUserData() != null){
                        JSONObject json = JSONObject.parseObject(msgSeekHelpInfoVO.getWechatUserData());
                        msgSeekHelpInfoVO.setHeadimgurl(json.get("headimgurl") == null ?  aliUrl+defaultAvatar :  json.getString("headimgurl"));
                        msgSeekHelpInfoVO.setNickname(json.get("nickname") == null ? "" :  json.getString("nickname"));
                    }
                }else if(msgSeekHelpInfoVO.getUserId() == -2){
                    msgSeekHelpInfoVO.setHeadimgurl( aliUrl+defaultAvatar);
                    msgSeekHelpInfoVO.setNickname("webApp用户");
                }else {
                    msgSeekHelpInfoVO.setHeadimgurl(FormatPhotoUrlUtil.formatString(aliUrl,msgSeekHelpInfoVO.getHeadimgurl()));
                }
            }

            //设置历史消息路径:只要是互动的语音消息都是本地的
            if(msgSeekHelpInfoVO.getMsgAttachmentAddr() == null){
                msgSeekHelpInfoVO.setMsgAttachmentAddr("");
            }else {
                if(msgSeekHelpInfoVO.getMsgContentType() == 1 || msgSeekHelpInfoVO.getMsgContentType() ==2){
                    if(msgSeekHelpInfoVO.getMsgType() == 0 && msgSeekHelpInfoVO.getMsgContentType() == 1){
                        msgSeekHelpInfoVO.setMsgAttachmentAddr(localUrl+msgSeekHelpInfoVO.getMsgAttachmentAddr());
                    }else {
                        msgSeekHelpInfoVO.setMsgAttachmentAddr(aliUrl+msgSeekHelpInfoVO.getMsgAttachmentAddr());
                    }
                }
            }
            //设置图片路径
            msgSeekHelpInfoVO.setPhotoInfo(FormatPhotoUrlUtil.formatStringArray(aliUrl,msgSeekHelpInfoVO.getPhotoInfo()));
            //设置求助语音消息路径
            if(msgSeekHelpInfoVO.getSeekVoice() == null || "".equals(msgSeekHelpInfoVO.getSeekVoice().replace(" ",""))){
                msgSeekHelpInfoVO.setSeekVoice("");
            }else {
                msgSeekHelpInfoVO.setSeekVoice(aliUrl+msgSeekHelpInfoVO.getSeekVoice());
            }

        }
        Map<String,Object> data = Maps.newLinkedHashMap();
        data.put("list",list);
        //更新时间
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String newLatestTime = formatter.format(currentTime);
        data.put("latestTime",newLatestTime);
        return  resultMap(data,errorCode,msg);

    }

    public Object updateMsgStatus(String ids, Integer status,Long curUserId,String curUserName) {
        int errorCode = 0 ;
        String msg = "操作失败";
        Date date = new Date();
        Map<String,Object> data = Maps.newLinkedHashMap();
        if(ids != null && !"".equals(ids)){
            String [] idsArr = ids.split(",");
            for (String id : idsArr) {
                baseMapper.updateMsgStatus(Long.parseLong(id), status,curUserId,curUserName,date);
                if(status == 2){
                    Msg curMsg = queryById(Long.parseLong(id));
                    if(curMsg != null){
                        userScoreService.autoAddUpScore(curMsg.getUserId(),curMsg.getRsId(),2);
                    }
                }
            }
            errorCode = 1 ;
            msg = "操作成功";
            data.put("result",1);
        }
        return resultMap(data,errorCode,msg);
    }

    public Object listMsgHis(Long rsId, Date beginMsgTime, Date endMsgTime, String msgAttachmentAddr) {
        String aliUrl = env.getProperty("oss.img.path");
        String localUrl = env.getProperty("native.resource.path");
        String defaultAvatar = env.getProperty("user.default.avatar");

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String beginMsgTimeStr = null;
        String endMsgTimeStr = null ;
        if(beginMsgTime != null){
            beginMsgTimeStr = formatter.format(beginMsgTime);
        }
        if(endMsgTime != null){
            endMsgTimeStr = formatter.format(endMsgTime);
        }

        Page<MsgSeekHelpInfoVO> page = baseMapper.listMsgHis(rsId,beginMsgTimeStr,endMsgTimeStr,msgAttachmentAddr);
        for (MsgSeekHelpInfoVO msgSeekHelpInfoVO : page.getRecords()){

            if(msgSeekHelpInfoVO.getMsgDirect() == 2){
                msgSeekHelpInfoVO.setNickname(msgSeekHelpInfoVO.getRsName());
                msgSeekHelpInfoVO.setHeadimgurl(aliUrl+msgSeekHelpInfoVO.getRsLogo());
            }else{
                if(msgSeekHelpInfoVO.getUserId() == -1){
                    if(msgSeekHelpInfoVO.getWechatUserData() != "" && msgSeekHelpInfoVO.getWechatUserData() != null){
                        JSONObject json = JSONObject.parseObject(msgSeekHelpInfoVO.getWechatUserData());
                        msgSeekHelpInfoVO.setHeadimgurl(json.get("headimgurl") == null ?  aliUrl+defaultAvatar :  json.getString("headimgurl"));
                        msgSeekHelpInfoVO.setNickname(json.get("nickname") == null ? "" :  json.getString("nickname"));
                    }
                }else if(msgSeekHelpInfoVO.getUserId() == -2){
                    msgSeekHelpInfoVO.setHeadimgurl( aliUrl+defaultAvatar);
                    msgSeekHelpInfoVO.setNickname("webApp用户");
                }else {
                    msgSeekHelpInfoVO.setHeadimgurl(FormatPhotoUrlUtil.formatString(aliUrl,msgSeekHelpInfoVO.getHeadimgurl()));
                }

            }
            //设置历史消息路径:只要是互动的语音消息都是本地的
            if(msgSeekHelpInfoVO.getMsgAttachmentAddr() == null){
                msgSeekHelpInfoVO.setMsgAttachmentAddr("");
            }else {
                if(msgSeekHelpInfoVO.getMsgContentType() == 1 || msgSeekHelpInfoVO.getMsgContentType() ==2){
                    if(msgSeekHelpInfoVO.getMsgType() == 0 && msgSeekHelpInfoVO.getMsgContentType() == 1){
                        msgSeekHelpInfoVO.setMsgAttachmentAddr(localUrl+msgSeekHelpInfoVO.getMsgAttachmentAddr());
                    }else {
                        msgSeekHelpInfoVO.setMsgAttachmentAddr(aliUrl+msgSeekHelpInfoVO.getMsgAttachmentAddr());
                    }
                }
            }
            //设置图片路径
            msgSeekHelpInfoVO.setPhotoInfo(FormatPhotoUrlUtil.formatStringArray(aliUrl,msgSeekHelpInfoVO.getPhotoInfo()));
            //设置图片路径
            msgSeekHelpInfoVO.setPhotoInfo(FormatPhotoUrlUtil.formatStringArray(aliUrl,msgSeekHelpInfoVO.getPhotoInfo()));
            //设置求助语音消息路径
            if(msgSeekHelpInfoVO.getSeekVoice() == null || "".equals(msgSeekHelpInfoVO.getSeekVoice().replace(" ",""))){
                msgSeekHelpInfoVO.setSeekVoice("");
            }else {
                msgSeekHelpInfoVO.setSeekVoice(aliUrl+msgSeekHelpInfoVO.getSeekVoice());
            }
        }
        return page;
    }

    public Object updateMsgStatusByTime(Long rsId,Date customizeTime, Integer status, Long curUserId, String curUserName) {
        int errorCode = 0 ;
        String msg = "操作失败";
        Date date = new Date();
        Map<String,Object> data = Maps.newLinkedHashMap();
        if(customizeTime != null){
            baseMapper.updateMsgStatusByTime(rsId,customizeTime, status,curUserId,curUserName,date);
            errorCode = 1 ;
            msg = "操作成功";
            data.put("result",1);
        }
        return resultMap(data,errorCode,msg);
    }

    public Object getNewMsgCount(Long rsId, Date latestTime,Integer status) {
        int errorCode = 0 ;
        String msg = "操作失败";
        Map<String,Object> data = Maps.newLinkedHashMap();
        EntityWrapper<Msg> msgWrapper = new EntityWrapper<>();
        if(status == 0){
            msgWrapper.eq("rs_id", rsId);
            msgWrapper.gt("msg_time",latestTime);
            msgWrapper.eq("msg_direct",0);
            msgWrapper.eq("del_status",0);
            msgWrapper.eq("status",0);
        }else {
            List<Integer> msgDirectList = new ArrayList<>();
            msgDirectList.add(0);
            msgDirectList.add(2);
            msgWrapper.eq("rs_id", rsId);
            msgWrapper.gt("msg_time",latestTime);
            msgWrapper.in("msg_direct",msgDirectList);
            msgWrapper.eq("del_status",0);
            msgWrapper.eq("status",1);
        }

        Integer newMsgsCount = selectCount(msgWrapper);
        errorCode = 1 ;
        msg = "操作成功";
        data.put("newMsgCount",newMsgsCount);
        return resultMap(data,errorCode,msg);
    }


    public Object replyMsg(String msgAttachmentAddr, Integer msgDirect, Long userId, Long rsId, Integer messageFrom, Long helpId) {
        String aliUrl = env.getProperty("oss.img.path");
        String localUrl = env.getProperty("native.resource.path");
        int errorCode = 0 ;
        String msgResult = "回复失败";
        Map<String,Object> data = Maps.newLinkedHashMap();
        Date date = new Date();

        Msg msg = new Msg();
        msg.setMsgTime(date);
        msg.setMsgType(5);
        msg.setMsgContentType(0);
        msg.setUserId(userId);
        msg.setRsId(rsId);
        msg.setMsgDirect(1);
        msg.setMsgAttachmentAddr(msgAttachmentAddr);
        msg.setStatus(0);
        msg.setMessageFrom(messageFrom);
        msg.setHelpId(helpId);
        msg.setDelStatus(0);
        Msg records = update(msg);
        data.put("msgTime",records.getMsgTime());
        data.put("msgType",records.getMsgType());
        data.put("msgContentType",records.getMsgContentType());
        data.put("userId",records.getUserId());
        data.put("rsId",records.getRsId());
        data.put("msgDirect",records.getMsgDirect());

        //设置历史消息路径:只要是互动的语音消息都是本地的
        if(records.getMsgAttachmentAddr() == null){
            data.put("msgAttachmentAddr","");
        }else {
            int imageMsgType = 2;
            if(records.getMsgContentType() == 1 || records.getMsgContentType() ==imageMsgType){
                if(records.getMsgType() == 0 && records.getMsgContentType() == 1){
                    records.setMsgAttachmentAddr(localUrl+records.getMsgAttachmentAddr());
                }else {
                    records.setMsgAttachmentAddr(aliUrl+records.getMsgAttachmentAddr());
                }
            }
        }
        data.put("status",records.getStatus());
        data.put("messageFrom",records.getMessageFrom());
        data.put("helpId",records.getHelpId());
        data.put("delStatus",records.getDelStatus());
        msgResult = "回复成功";
        errorCode = 1;

        RadioStation radioStation = radioStationService.queryById(rsId);
        if(rsId != null && radioStation != null && userId != null){
            logger.info("=========================准备推送消息,用户ID："+userId+";电台ID："+rsId);
            AliyunPushUtil.pushMessageToAndroidByAlias(userId.toString(),"导播回复消息",Integer.parseInt(rsId.toString()),radioStation.getRsCode(),radioStation.getRsName(),msgAttachmentAddr,aliUrl+radioStation.getRsLogo());
        }else {
            logger.info("=========================消息推送失败,用户ID："+userId+";电台ID："+rsId);
        }

        return resultMap(data,errorCode,msgResult);

    }


    public Object delMsgs(String ids) {
        int errorCode = 0 ;
        String msg = "删除失败";
        Map<String,Object> data = Maps.newLinkedHashMap();
        if(!"".equals(ids)){
            String[] idsArr = ids.split(",");
            for (String id : idsArr){
                msgService.delMsg(Long.parseLong(id));
            }
        }
        errorCode = 1 ;
        msg = "删除成功";
        data.put("result",1);
        return resultMap(data,errorCode,msg);
    }

    public Object analysisIndex(Long rsId) {
        int errorCode = 0 ;
        String msg = "获取数据失败";
        Map<String,Object> data = Maps.newLinkedHashMap();
        //获取当天的开始时间和结束时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date startDate = calendar.getTime();
        calendar.set(Calendar.HOUR_OF_DAY,23);
        calendar.set(Calendar.MINUTE,59);
        calendar.set(Calendar.SECOND,59);
        Date endDate = calendar.getTime();

        //消息总量 今日消息量
        EntityWrapper<Msg> totalMsgWrapper = new EntityWrapper<>();
        totalMsgWrapper.eq("rs_id",rsId);
        Integer totalMsg = selectCount(totalMsgWrapper);

        EntityWrapper<Msg> totalDayMsgWrapper = new EntityWrapper<>();
        totalDayMsgWrapper.eq("rs_id",rsId);
        totalDayMsgWrapper.gt("msg_time",startDate);
        totalDayMsgWrapper.lt("msg_time",endDate);
        Integer totalDayMsg = selectCount(totalDayMsgWrapper);

        //待审消息量 今日待审核消息量
        EntityWrapper<Msg> unauditMsgWrapper = new EntityWrapper<>();
        unauditMsgWrapper.eq("rs_id",rsId);
        unauditMsgWrapper.eq("status",0);
        Integer unauditMsg = selectCount(unauditMsgWrapper);

        EntityWrapper<Msg> unauditDayMsgWrapper = new EntityWrapper<>();
        unauditDayMsgWrapper.eq("rs_id",rsId);
        unauditDayMsgWrapper.eq("status",0);
        unauditDayMsgWrapper.gt("msg_time",startDate);
        unauditDayMsgWrapper.lt("msg_time",endDate);
        Integer unauditDayMsg = selectCount(unauditDayMsgWrapper);

        //待播放消息量 今日待播放消息量
        EntityWrapper<Msg> playMsgWrapper = new EntityWrapper<>();
        playMsgWrapper.eq("rs_id",rsId);
        playMsgWrapper.eq("status",1);
        Integer playMsg = selectCount(playMsgWrapper);

        EntityWrapper<Msg> playDayMsgWrapper = new EntityWrapper<>();
        playDayMsgWrapper.eq("rs_id",rsId);
        playDayMsgWrapper.eq("status",1);
        playDayMsgWrapper.gt("msg_time",startDate);
        playDayMsgWrapper.lt("msg_time",endDate);
        Integer playDayMsg = selectCount(playDayMsgWrapper);

        //粉丝总量
        EntityWrapper<RadioStationFollower> followerWrapper = new EntityWrapper<>();
        followerWrapper.eq("rs_id",rsId);
        Integer follower =  radioStationFollowerService.selectCount(followerWrapper);

        EntityWrapper<RadioStationFollower> followerDayWrapper = new EntityWrapper<>();
        followerDayWrapper.eq("rs_id",rsId);
        followerDayWrapper.gt("follow_time",startDate);
        followerDayWrapper.lt("follow_time",endDate);
        Integer followerDay =  radioStationFollowerService.selectCount(followerDayWrapper);

        data.put("totalMsg",totalMsg);
        data.put("totalDayMsg",totalDayMsg);
        data.put("unauditMsg",unauditMsg);
        data.put("unauditDayMsg",unauditDayMsg);
        data.put("playMsg",playMsg);
        data.put("playDayMsg",playDayMsg);
        data.put("follower",follower);
        data.put("followerDay",followerDay);

        errorCode = 1 ;
        msg = "获取数据成功";

        return resultMap(data,errorCode,msg);
    }

}
